<?php
/**
 * Description of Controller
 *
 * @author henson
 */

class Controller
{

	private $_towhere;
	
	private $router = null;
	/**
	 * core class, the key of the array is the classname , 
	 *  the value of the array is the class path
	 */
	private static $_classCore = array(
		'smarty'=>'smarty/Smarty.class.php',
		'router' => 'router.php',
		'base' => 'class.base.php',
		'curl'	 => 'class.curl.php',
		'view' => 'view.php',
		'mysql' => 'mysql.php',
		'page' => 'class.page.php',	
	);

	private static $_includeDir = array('include','model');

	/**
	 * get inlcude file
	 */
	public function __construct()
	{

		set_include_path(get_include_path() . PATH_SEPARATOR . _ROOT . '/' . implode(PATH_SEPARATOR . _ROOT . '/', self::$_includeDir));
		
		$this->router = new Router();
	}
	/**
	 * get the data and display
	 *
	 */
	public function run()
	{
		global $_CFG;
		$this->_towhere = $this->router->getRouter();
		$module = ucfirst($this->_towhere->module).'Controller';
		$action = $this->_towhere->action.'Action';
		include_once( _ROOT . '/controller/'. $this->_towhere->module. 'Controller.php');
		$obj = new $module();
		if(method_exists($obj, $action))
		{
			
			$_CFG['ROUTE']['MODULE'] = $this->_towhere->module;
			$_CFG['ROUTE']['ACTION'] = $this->_towhere->action;
			$obj->$action();
			die;
		}
		else 
		{
			echo "router defined is wrong";
			exit();
		}
	}
	/**
	 * auto include
	 *
	 */
    public static function autoload($classname)
	{
		$classname = strtolower($classname);
		if(isset(self::$_classCore[$classname]))
		{
			include_once( self::$_classCore[$classname] );
		}
		elseif(file_exists(_ROOT . '/model/class.' . $classname . '.php'))
		{
			include_once( 'class.' . $classname . '.php' );
		}
		else
		{
			echo $classname." class is not defined";
			exit();
		}

	}

	

}

spl_autoload_register(array('Controller','autoload'));